package com.stud.system.controller.common;

import com.alibaba.fastjson2.JSONObject;
import com.google.code.kaptcha.Producer;
import com.stud.common.properties.StudProperties;
import com.stud.common.constant.CacheConstants;
import com.stud.common.constant.Constants;
import com.stud.common.core.domain.AjaxResult;
import com.stud.common.core.redis.RedisCache;
import com.stud.common.utils.PhoneMessageUtil;
import com.stud.common.utils.StringUtils;
import com.stud.common.utils.Toolkit;
import com.stud.common.utils.sign.Base64;
import com.stud.common.utils.uuid.IdUtils;
import com.stud.system.service.SysConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author Stud
 */
@Tag(name = "验证码发送校验")
@RestController
@Slf4j
public class CaptchaController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysConfigService configService;

    @Value("${spring.profiles.active}")
    private String env;

    @Operation(summary = "生成图片验证码")
    @GetMapping("/captchaImage")
    public AjaxResult captchaImage() {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null;
        String code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = StudProperties.getCaptchaType();
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }

    @Operation(summary = "生成图片验证码")
    @GetMapping("/captchaImg")
    public AjaxResult captchaImg() {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("captchaEnabled", true);
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = StudProperties.getCaptchaType();
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }

    @Operation(summary = "校验图片验证码")
    @GetMapping("/validateCaptcha")
    public AjaxResult validateCaptcha(String uuid, String captchaCode) {

        if (StringUtils.isBlank(uuid) || StringUtils.isBlank(captchaCode)) {
            return AjaxResult.error("参数异常");
        }

        uuid = Toolkit.xssEncode(uuid);
        captchaCode = Toolkit.xssEncode(captchaCode);

        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);

        if (captcha == null) {
            return AjaxResult.error("验证码已失效");
        }
        if (!Objects.equals(captcha, captchaCode)) {
            return AjaxResult.error("验证码错误");
        }
        return AjaxResult.success();
    }

    @Operation(summary = "生成短信验证码")
    @GetMapping("/messageCode")
    public AjaxResult messageCode(String phone) {
        if (StringUtils.isBlank(phone)) {
            return AjaxResult.error("手机号错误");
        }

        phone = Toolkit.xssEncode(phone);

        AjaxResult ajax = AjaxResult.success();

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.MESSAGE_CODE_KEY + uuid + phone;

        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));

        JSONObject params = new JSONObject();
        params.put("code", code);
        PhoneMessageUtil.send(params, phone);
        redisCache.setCacheObject(verifyKey, code, Constants.MESSAGE_EXPIRATION, TimeUnit.MINUTES);

        ajax.put("uuid", uuid);

        if (Objects.equals(env, "dev") || Objects.equals(env, "test")) {
            ajax.put("messageCode", code);
        }
        return ajax;
    }

    @Operation(summary = "校验手机验证码")
    @GetMapping("/validateMessageCode")
    public AjaxResult validateMessageCode(String uuid, String phone, String messageCode) {
        PhoneMessageUtil.validateMessageCode(uuid, phone, messageCode);
        return AjaxResult.success();
    }
}
